package com.ldy.core.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ldy.core.entity.BaseMenu;
import com.ldy.core.entity.BaseRole;
import com.ldy.core.entity.BaseRoleMenu;
import com.ldy.core.mapper.BaseRoleMapper;
import com.ldy.core.service.BaseRoleMenuService;
import com.ldy.core.service.BaseRoleService;
import com.ldy.core.vo.RoleVO;

import cn.hutool.core.collection.CollectionUtil;

@Service
@Transactional
public class BaseRoleServiceImpl  extends ServiceImpl<BaseRoleMapper, BaseRole> implements BaseRoleService{

	@Autowired
	private BaseRoleMenuService roleMenuService;
	
	@Override
	public void saveHandle(RoleVO role) {
		Date now = new Date();
		role.setLastUpdateTime(now);
		if (StringUtils.hasText(role.getId())) {
			baseMapper.updateById(role);
			// 删除角色菜单关系
			QueryWrapper<BaseRoleMenu> query = new QueryWrapper<>();
			query.eq("role_id", role.getId());
			roleMenuService.remove(query);
		} else {
			role.setCreateTime(now);
			baseMapper.insert(role);
		}
		// 新增角色菜单关系
		List<BaseMenu> menus = role.getMenus();
		List<BaseRoleMenu> roleMenus = new ArrayList<BaseRoleMenu>();
		for (BaseMenu m: menus) {
			BaseRoleMenu roleMenu = new BaseRoleMenu();
			roleMenu.setAppId(m.getAppId());
			roleMenu.setRoleId(role.getId());
			roleMenu.setMenu(m.getMenuUri());
			roleMenus.add(roleMenu);
		}
		if (CollectionUtil.isNotEmpty(roleMenus)) {
			roleMenuService.saveBatch(roleMenus);
		}
	}

}
